class AuthD::Request
	IPC::JSON.message SearchUser, 12 do
		property regex : String? = nil

		# Since the list could be long, here is a way to get it at a reasonable pace.
		property offset : Int32 = 0
		# By default, authd will send 10 users at a time.

		def initialize(@regex = nil, @offset = 0)
		end

		def to_s(io : IO)
			super io
			io << " (regex: #{@regex}, offset: #{@offset})"
		end

		def handle(authd : AuthD::Service, fd : Int32)
			logged_user = authd.get_logged_user_full? fd
			return Response::ErrorMustBeAuthenticated.new if logged_user.nil?
			logged_user.assert_permission("authd", "*", User::PermissionLevel::Read)

			users = authd.users.to_a
			matching_users = Array(AuthD::User::Public).new

			# FIXME: could be optimized.
			result = if regex = @regex
				pattern = Regex.new regex, Regex::Options::IGNORE_CASE
				users.each do |u|
					puts "trying to match user #{u.login}"
					if pattern =~ u.login || u.profile.try do |profile|
								full_name = profile["full_name"]?
								puts "login didn't work, trying to match its full name: #{full_name}"
								if full_name.nil?
									false
								else
									pattern =~ full_name.as_s
								end
							end || u.contact.email.try do |email|
								puts "full name didn't work, trying to match its email: #{email}"
								pattern =~ email
							end
						Baguette::Log.debug "#{u.login} matches #{pattern}"
						matching_users << u.to_public
					else
						Baguette::Log.debug "#{u.login} doesn't match #{pattern}"
					end
				end
				matching_users[offset..offset+10]
			else
				users[offset..offset+10].each do |u|
					matching_users << u.to_public
				end
				matching_users
			end

			Response::MatchingUsers.new result
		end
	end
	AuthD.requests << SearchUser
end
